//
//  SendQueryToDB.m
//  ExchangeClient
//
//  Created by Антон on 03.12.12.
//  Copyright (c) 2012 Сураева Яна. All rights reserved.
//

#import "SendQueryToDB.h"
#import <sqlite3.h>

@implementation SendQueryToDB
+(void) insertOrDeleteQuery:(NSString *)query{
    static sqlite3 *database = nil;
    sqlite3_stmt *insertstmt;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];

    
    NSString *path=[documentsDirectory stringByAppendingPathComponent:@"FoldersForMail"];

    if (sqlite3_open([path UTF8String], &database) == SQLITE_OK) {
        
        if (sqlite3_prepare_v2(database, [query cStringUsingEncoding:NSUTF8StringEncoding], -1, &insertstmt, NULL) != SQLITE_OK) {
            NSAssert1(0, @"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(database));
        }
        int success = sqlite3_step(insertstmt);
        if (success != SQLITE_ERROR) {
            NSLog(@"error");
        }
    }
    sqlite3_close(database);
    
}

+(NSMutableArray*) selectQuery:(NSString *)query{
    NSMutableArray *array=[[NSMutableArray new]autorelease];
    static sqlite3 *database = nil;
    sqlite3_stmt *selectstmt;
    

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory= [paths objectAtIndex:0];
    NSString *path= [documentsDirectory stringByAppendingPathComponent:@"FoldersForMail"];
    
     
    if (sqlite3_open([path UTF8String], &database) == SQLITE_OK) {
        NSString *sql = [[[NSString alloc]initWithString:@"SELECT name FROM users"]autorelease];
        if(sqlite3_prepare_v2(database, [sql cStringUsingEncoding:NSUTF8StringEncoding], -1, &selectstmt, NULL) == SQLITE_OK) {
            while(sqlite3_step(selectstmt) == SQLITE_ROW) {
                NSString *folderObj = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 0)];
                
                [array addObject:folderObj];
                
            }
        }
    }
    else
        sqlite3_close(database);
    return array;
}

@end
